#include "ChooseLevelState.h"
#include "ResMgr.h"
#include "Texture.h"
#include "AnimationSprite.h"
#include "Animation.h"
#include "Button.h"
#include "Utils.h"
#include "GameUtils.h"
#include "Box.h"
#include "Level.h"
#include "PlayState.h"
#include "StateMgr.h"
#include "GameCommonInfo.h"

ChooseLevelState::ChooseLevelState()
{

}

void ChooseLevelState::Init()
{
	ResMgr::GetInstance()->LoadChooseLevelRes();
	background = ResMgr::GetInstance()->GetTexture(TID_MAIN_MENU_BACK);
	aniSprite = new AnimationSprite();
	Animation* ani = new Animation(0);
	ani->GenerateAuto(ResMgr::GetInstance()->GetTexture(TID_LEVELS_BUTTON),
		W_LEVEL_BUTTON_SPRITE, H_LEVEL_BUTTON_SPRITE, 2, 0, 17, 0);
	aniSprite->AddAnimation(ani);

	Button* button;

	for(int i = 0; i < NUM_LEVEL; i++)
	{
		button = new Button(X_BUTTON_LEVEL+ DX_BUTTON*(i%3), 
			Y_BUTTON_LEVEL+ DY_BUTTON*(i/3), 
			W_LEVEL_BUTTON_SPRITE, H_LEVEL_BUTTON_SPRITE);
		button->SetImageForTouchUp(aniSprite, 0, 2*i);
		button->SetImageForTouchDown(aniSprite, 0, 2*i+1);
		button->SetID(i);
		buttons.push_back(button);
	}
}

void ChooseLevelState::Render()
{
	background->Render(0, 0);
	for(int i = 0; i < buttons.size(); i++)
		buttons[i]->Render();
}

void ChooseLevelState::TouchDown(int x, int y)
{
	for(int i = 0; i < NUM_LEVEL; i++)
	{

		if(buttons[i]->IsTouchDownBy(x, y) == true)
		{
			buttons[i]->TouchDown();
			OnButtonClick(buttons[i], BTE_TOUCH_DOWN);
		}
	}
}

void ChooseLevelState::TouchUp(int x, int y)
{
	for(int i = 0; i < NUM_LEVEL; i++)
	{

		if(buttons[i]->IsTouchUpBy(x, y) == true)
		{
			buttons[i]->TouchUp();
			OnButtonClick(buttons[i], BTE_TOUCH_UP);
		}
	}
}

void ChooseLevelState::OnButtonClick(Button* sender, int e)
{
	if(e == BTE_TOUCH_UP)
	{
		PlayState* playState = PlayState::GetInstance();
		GameCommonInfo::GetInstance()->SetCurLevel(sender->GetID());
		StateMgr::GetInstance()->SwitchState(PlayState::GetInstance());
	}
}
ChooseLevelState::~ChooseLevelState()
{
	for(int i = 0; i < NUM_LEVEL; i++)
	{
		DELETE_SAFELY(buttons[i]);
	}
	buttons.clear();

	DELETE_SAFELY(aniSprite);
	ResMgr::GetInstance()->UnloadChooseLevelRes();
}